import React, { useState, useEffect, useCallback } from 'react';
import {
  List,
  Card,
  Select,
  Button,
  Empty,
  Space,
  Tag,
  Typography,
  Divider,
  message,
  Spin,
  Slider,
  Popover,
} from 'antd';
import {
  DeleteOutlined,
  LineChartOutlined,
  BarChartOutlined,
  AreaChartOutlined,
  DotChartOutlined,
  WarningOutlined,
  CheckCircleOutlined,
  SwapOutlined,
  PieChartOutlined,
  SettingOutlined,
} from '@ant-design/icons';
import { useParams } from 'react-router-dom';
import { useVisualization, ChartType } from '../../contexts/VisualizationContext';
import { useNavigation } from '../../contexts/NavigationContext';
import { experimentApi } from '../../services/api';
import ChartRenderer from '../charts/charts/ChartRenderer';
import { generateColors, generateBorderColors } from '../../utils/colorUtils';
import LineStyleControls from './LineStyleControls';
import SteppedLineControls from './SteppedLineControls';
import ChartDisplay from './ChartDisplay';

const { Title, Text, Paragraph } = Typography;
const { Option } = Select;

const VisualizationPanel: React.FC = () => {
  const { projectId } = useParams<{ projectId: string }>();
  const {
    visualizationItems,
    removeVisualizationItem,
    updateChartType,
    clearAll,
  } = useVisualization();
  const { navigateToSeries } = useNavigation();

  // 图表数据和加载状态
  const [chartData, setChartData] = useState<any>(null);
  const [loading, setLoading] = useState(false);
  const [chartVisible, setChartVisible] = useState(false);
  
  // 视图模式：'horizontal' 横向展示（默认）或 'vertical' 纵向对比
  const [viewMode, setViewMode] = useState<'horizontal' | 'vertical'>('horizontal');
  
  // 纵向对比模式下选中的数据组索引（时间点）
  const [selectedDataIndex, setSelectedDataIndex] = useState<number>(0);
  
  // 纵向模式下存储所有时间点的数据
  const [verticalDataLabels, setVerticalDataLabels] = useState<(string | number)[]>([]);
  const [verticalDataValues, setVerticalDataValues] = useState<number[][]>([]);
  
  // 记录横向和纵向模式的图表类型，以便切换模式时恢复
  const [horizontalChartTypes, setHorizontalChartTypes] = useState<Record<string, ChartType>>({});
  const [verticalChartType, setVerticalChartType] = useState<ChartType>('bar');

  // 折线图样式与标记样式（仅在横向模式并使用折线图时生效）
  const [lineStyleOptions, setLineStyleOptions] = useState<{ borderWidth: number; tension: number; dashed: boolean }>(
    { borderWidth: 2, tension: 0.1, dashed: false }
  );
  const [markerOptions, setMarkerOptions] = useState<{ pointRadius: number }>(
    { pointRadius: 3 }
  );

  // 每个可视化项（仅折线）单独的样式覆盖：标记形状、线条实/虚
  const [perSeriesLineOverrides, setPerSeriesLineOverrides] = useState<Record<string, { pointStyle?: 'circle' | 'cross' | 'crossRot' | 'dash' | 'line' | 'rect' | 'rectRounded' | 'rectRot' | 'star' | 'triangle'; dashed?: boolean }>>({});

  // 阶梯折线统一样式
  const [steppedOptions, setSteppedOptions] = useState<{ mode: 'before' | 'after' | 'middle'; borderWidth: number }>({ mode: 'before', borderWidth: 2 });

  // 散点图统一样式与每条覆盖
  const [scatterOptions, setScatterOptions] = useState<{ pointRadius: number }>({ pointRadius: 4 });
  const [perSeriesScatterOverrides, setPerSeriesScatterOverrides] = useState<Record<string, { pointStyle?: 'circle' | 'cross' | 'crossRot' | 'dash' | 'line' | 'rect' | 'rectRounded' | 'rectRot' | 'star' | 'triangle' }>>({});

  // 横向模式的图表类型选项（不支持饼图和甜甜圈图，雷达图只允许统一选择）
  const horizontalChartTypeOptions: { value: ChartType; label: string; icon: React.ReactNode }[] = React.useMemo(() => [
    { value: 'line', label: '折线图', icon: <LineChartOutlined /> },
    { value: 'stepped-line', label: '阶梯折线', icon: <LineChartOutlined /> },
    { value: 'bar', label: '柱状图', icon: <BarChartOutlined /> },
    { value: 'area', label: '面积图', icon: <AreaChartOutlined /> },
    { value: 'scatter', label: '散点图', icon: <DotChartOutlined /> },
    { value: 'stacked', label: '柱状堆叠', icon: <BarChartOutlined /> },
    { value: 'stacked-line', label: '折线堆叠', icon: <LineChartOutlined /> },
    { value: 'stacked-area', label: '面积堆叠', icon: <AreaChartOutlined /> },
    { value: 'radar', label: '雷达图', icon: <AreaChartOutlined /> },
  ], []);

  // 纵向模式的图表类型选项（只支持柱状图、饼图、甜甜圈图，不支持堆叠图）
  const verticalChartTypeOptions: { value: ChartType; label: string; icon: React.ReactNode }[] = React.useMemo(() => [
    { value: 'bar', label: '柱状图', icon: <BarChartOutlined /> },
    { value: 'pie', label: '饼图', icon: <PieChartOutlined /> },
    { value: 'doughnut', label: '甜甜圈图', icon: <PieChartOutlined /> },
    { value: 'radar', label: '雷达图', icon: <AreaChartOutlined /> },
  ], []);

  // 根据视图模式获取可用的图表类型
  const chartTypeOptions = viewMode === 'vertical' ? verticalChartTypeOptions : horizontalChartTypeOptions;

  // 计算当前是否为“统一图表类型”，若统一则返回该类型，否则返回 undefined
  const unifiedChartType = React.useMemo<ChartType | undefined>(() => {
    if (visualizationItems.length > 0) {
      const firstType = visualizationItems[0].chartType;
      const allSame = visualizationItems.every(item => item.chartType === firstType);
      return allSame ? firstType : undefined;
    }
    return undefined;
  }, [visualizationItems]);

  // 全局切换所有图表类型
  const handleChangeAllChartType = (value: ChartType) => {
    visualizationItems.forEach(item => updateChartType(item.id, value));
    // 根据模式更新保存的图表类型
    if (viewMode === 'vertical') {
      setVerticalChartType(value);
    } else {
      // 横向模式下，更新所有项目的保存类型
      const newTypes: Record<string, ChartType> = {};
      visualizationItems.forEach(item => {
        newTypes[item.id] = value;
      });
      setHorizontalChartTypes(newTypes);
    }
  };

  // 检查是否有雷达图类型（雷达图只允许统一选择）
  const hasRadarChart = React.useMemo(() => {
    return visualizationItems.some(item => item.chartType === 'radar');
  }, [visualizationItems]);

  // 当统一图表类型是雷达图时，确保新添加的数据也自动设置为雷达图
  // 或者当有雷达图类型时，强制所有项目都变成雷达图（因为雷达图只能统一选择）
  useEffect(() => {
    if (viewMode === 'horizontal' && visualizationItems.length > 0) {
      // 检查是否有雷达图类型
      const hasRadar = visualizationItems.some(item => item.chartType === 'radar');
      
      if (hasRadar) {
        // 如果有雷达图类型，强制所有项目都变成雷达图（雷达图只能统一选择）
        const nonRadarItems = visualizationItems.filter(item => item.chartType !== 'radar');
        if (nonRadarItems.length > 0) {
          // 自动将所有非雷达图类型的项目更新为雷达图
          nonRadarItems.forEach(item => {
            updateChartType(item.id, 'radar');
          });
          // 更新保存的横向图表类型
          const newTypes: Record<string, ChartType> = {};
          visualizationItems.forEach(item => {
            newTypes[item.id] = 'radar';
          });
          setHorizontalChartTypes(newTypes);
        }
      }
    }
  }, [visualizationItems, viewMode, updateChartType]);

  // 获取第一个数据的长度（作为标准长度）
  const firstDataLength = visualizationItems.length > 0 ? visualizationItems[0].dataLength : null;

  // 检查所有数据长度是否一致
  const allLengthsMatch = React.useMemo(() => {
    if (visualizationItems.length === 0) return true;
    if (!firstDataLength) return true;
    return visualizationItems.every(item => item.dataLength === firstDataLength);
  }, [visualizationItems, firstDataLength]);

  // 处理清空所有，同时清除图表状态
  const handleClearAll = () => {
    clearAll();
    setChartData(null);
    setChartVisible(false);
    setLoading(false);
  };

  // 找出长度不一致的数据
  const inconsistentItems = React.useMemo(() => {
    if (!firstDataLength) return [];
    return visualizationItems.filter(item => item.dataLength !== firstDataLength);
  }, [visualizationItems, firstDataLength]);

  // 获取序列数据
  const fetchSeriesData = async (experimentId: number, seriesId: number, dataLength: number) => {
    if (!projectId) {
      throw new Error('项目ID不存在');
    }

    // 根据数据长度决定获取的数据量
    const limit = Math.min(dataLength, 10000); // 限制最多获取10000条数据
    const result = await experimentApi.getSeriesData(projectId, experimentId, seriesId, 0, limit);
    
    return result;
  };

  // 从数据中提取数值列（排除索引列）
  const extractNumericData = (data: any[], columns: Array<{ name: string; type: string }>, indexColumnName?: string) => {
    if (!data || data.length === 0) {
      return { labels: [], values: [] };
    }

    // 获取索引列（通常是第一列或指定的索引列）
    let labels: (string | number)[] = [];
    if (indexColumnName && columns.some(col => col.name === indexColumnName)) {
      labels = data.map(row => row[indexColumnName] ?? row[0]);
    } else if (columns.length > 0) {
      // 使用第一列作为索引
      const firstColumnName = columns[0].name;
      labels = data.map(row => row[firstColumnName] ?? row[0] ?? '');
    } else {
      // 如果没有列信息，使用索引
      labels = data.map((_, index) => index);
    }

    // 提取数值列
    const numericColumns = columns.filter(col => {
      const type = col.type.toLowerCase();
      return (type === 'integer' || type === 'float' || type === 'double' || type === 'number') &&
             col.name !== indexColumnName;
    });

    // 如果只有一个数值列，直接使用；否则使用第一个数值列
    const valueColumn = numericColumns.length > 0 ? numericColumns[0] : columns[1] || columns[0];
    const values = data.map(row => {
      const val = row[valueColumn.name];
      return typeof val === 'number' ? val : parseFloat(val) || 0;
    });

    return { labels, values };
  };

  // 创建一个唯一键，用于跟踪可视化项的变化（只关注影响图表的关键属性）
  const visualizationItemsKey = React.useMemo(() => {
    if (viewMode === 'vertical') {
      return visualizationItems.map(item => `${item.id}:${item.chartType}`).join(',') + `:${viewMode}:${selectedDataIndex}`;
    }
    return visualizationItems.map(item => `${item.id}:${item.chartType}`).join(',') + `:${viewMode}`;
  }, [visualizationItems, viewMode, selectedDataIndex]);
  
  // 检测状态不一致：如果viewMode是horizontal但图表类型是纵向模式才有的类型，说明状态不一致
  // 这可能发生在切换页面后，viewMode被重置但图表类型仍保留
  useEffect(() => {
    if (viewMode === 'horizontal' && visualizationItems.length > 0) {
      const verticalOnlyTypes: ChartType[] = ['pie', 'doughnut'];
      const hasVerticalType = visualizationItems.some(item => verticalOnlyTypes.includes(item.chartType));
      
      // 如果发现状态不一致（横向模式但图表类型是纵向模式才有的），恢复横向模式的图表类型
      if (hasVerticalType) {
        // 先尝试从保存的类型恢复
        let hasSavedTypes = false;
        visualizationItems.forEach(item => {
          const savedType = horizontalChartTypes[item.id];
          if (savedType && !verticalOnlyTypes.includes(savedType)) {
            updateChartType(item.id, savedType);
            hasSavedTypes = true;
          }
        });
        
        // 如果没有保存的类型，或者保存的类型也是纵向类型，使用默认的bar
        if (!hasSavedTypes) {
          visualizationItems.forEach(item => {
            if (verticalOnlyTypes.includes(item.chartType)) {
              updateChartType(item.id, 'bar');
            }
          });
        }
      }
    }
  }, [viewMode, visualizationItems, horizontalChartTypes, updateChartType]);

  // 当切换到纵向模式时，如果当前图表类型不支持，自动切换为柱状图
  // 但只有在第一次切换或图表类型不符合时才更新，避免覆盖已保存的纵向图表类型
  useEffect(() => {
    if (viewMode === 'vertical') {
      const allowedTypes: ChartType[] = ['bar', 'pie', 'doughnut', 'radar'];
      visualizationItems.forEach(item => {
        if (!allowedTypes.includes(item.chartType)) {
          // 如果当前类型不支持，使用保存的纵向类型或默认bar
          const newType = verticalChartType || 'bar';
          updateChartType(item.id, newType);
        }
      });
    }
  }, [viewMode, visualizationItems, updateChartType, verticalChartType]);

  // 样式调整即时生效：当折线样式或标记样式变化时，直接更新当前 chartData 中的折线数据集样式
  useEffect(() => {
    if (viewMode !== 'horizontal') return;
    if (!chartData || !chartData.datasets) return;
    const updated = {
      ...chartData,
      datasets: chartData.datasets.map((ds: any) => {
        if (ds.type === 'scatter') {
          // scatter
          const next: any = { ...ds };
          const override = ds.__vizId ? perSeriesScatterOverrides[ds.__vizId] : undefined;
          next.pointRadius = scatterOptions.pointRadius;
          if (override?.pointStyle) next.pointStyle = override.pointStyle;
          return next;
        }
        if (ds.type === 'line' && !ds.stepped) {
          const next: any = { ...ds };
          // 如果该系列存在单独覆盖，则使用覆盖；否则使用全局
          const override = ds.__vizId ? perSeriesLineOverrides[ds.__vizId] : undefined;
          const dashed = override?.dashed !== undefined ? override.dashed : lineStyleOptions.dashed;
          next.tension = lineStyleOptions.tension;
          next.borderWidth = lineStyleOptions.borderWidth;
          next.pointRadius = markerOptions.pointRadius;
          if (override?.pointStyle !== undefined) {
            next.pointStyle = override.pointStyle;
          }
          next.borderDash = dashed ? [6, 4] : undefined;
          return next;
        }
        if (ds.type === 'line' && ds.stepped) {
          const next: any = { ...ds };
          const override = ds.__vizId ? perSeriesLineOverrides[ds.__vizId] : undefined;
          const dashed = override?.dashed;
          next.stepped = steppedOptions.mode;
          next.tension = 0;
          next.borderWidth = steppedOptions.borderWidth;
          next.pointRadius = markerOptions.pointRadius;
          if (override?.pointStyle !== undefined) {
            next.pointStyle = override.pointStyle;
          }
          next.borderDash = dashed ? [6, 4] : undefined;
          return next;
        }
        return ds;
      })
    };
    setChartData(updated);
  }, [lineStyleOptions, markerOptions, perSeriesLineOverrides, perSeriesScatterOverrides, scatterOptions, steppedOptions, viewMode]);

  // 当数据组数量变化时，如果当前索引超出范围，重置为0
  useEffect(() => {
    if (viewMode === 'vertical' && verticalDataLabels.length > 0 && selectedDataIndex >= verticalDataLabels.length) {
      setSelectedDataIndex(0);
    }
  }, [viewMode, verticalDataLabels.length, selectedDataIndex]);

  // 记录上一次的 visualizationItemsKey，用于判断是否真的变化了
  const prevVisualizationItemsKeyRef = React.useRef<string>('');

  // 生成图表（自动调用，不显示错误提示）
  const handleRenderChart = useCallback(async (showError = false) => {
    if (visualizationItems.length === 0) {
      if (showError) {
        message.warning('请先添加需要可视化的数据');
      }
      return;
    }

    // 长度校验
    if (!allLengthsMatch) {
      if (showError) {
        message.error('所有数据的长度必须一致才能生成图表，请检查数据长度');
      }
      return;
    }

    if (!projectId) {
      if (showError) {
        message.error('项目ID不存在');
      }
      return;
    }

    try {
      setLoading(true);
      setChartVisible(false);

      // 获取所有序列数据
      const dataPromises = visualizationItems.map(item =>
        fetchSeriesData(item.experimentId, item.seriesId, item.dataLength)
      );

      const results = await Promise.all(dataPromises);

      // 生成颜色
      const colors = generateColors(visualizationItems.length, 0.6);
      const borderColors = generateBorderColors(visualizationItems.length);

      // 准备图表数据
      let chartDataResult: any;

      if (viewMode === 'vertical') {
        // 纵向对比模式：转换数据格式，每个时间点作为一个数据点，包含所有序列的值
        const allLabels: (string | number)[] = [];
        const allValues: number[][] = []; // 每个元素是一个时间点的所有序列值

        // 首先提取所有数据
        for (let i = 0; i < visualizationItems.length; i++) {
          const result = results[i];
          const { labels: itemLabels, values } = extractNumericData(
            result.data,
            result.columns,
            undefined
          );

          // 使用第一个数据集的标签
          if (i === 0) {
            allLabels.push(...itemLabels);
            // 初始化allValues数组
            for (let j = 0; j < itemLabels.length; j++) {
              allValues.push([]);
            }
          }

          // 将当前序列的值添加到对应时间点
          for (let j = 0; j < values.length; j++) {
            if (allValues[j]) {
              allValues[j].push(values[j]);
            }
          }
        }

        // 保存纵向模式的所有数据
        setVerticalDataLabels(allLabels);
        setVerticalDataValues(allValues);

        // 获取选中的数据组（时间点）的数据
        const selectedTimePointValues = allValues[selectedDataIndex] || [];
        const selectedLabel = allLabels[selectedDataIndex] || `数据组 ${selectedDataIndex + 1}`;

        // 获取第一个项目的图表类型（纵向模式下，所有项目使用相同的图表类型）
        const firstItemChartType = visualizationItems[0]?.chartType || 'bar';
        
        // 准备图表数据：显示选定时间点下所有序列的对比
        const seriesLabels = visualizationItems.map(item => 
          `${item.seriesName}${item.seriesUnit ? ` (${item.seriesUnit})` : ''}`
        );

        chartDataResult = {
          labels: seriesLabels,
          datasets: [{
            label: String(selectedLabel),
            data: selectedTimePointValues,
            type: firstItemChartType,
            backgroundColor: colors.slice(0, visualizationItems.length),
            borderColor: borderColors.slice(0, visualizationItems.length),
            borderWidth: 2,
          }],
        };
      } else {
        // 横向模式：原有逻辑（每个序列作为一个数据集）
        const datasets: any[] = [];
        let labels: (string | number)[] = [];

        for (let i = 0; i < visualizationItems.length; i++) {
          const item = visualizationItems[i];
          const result = results[i];

          // 提取数据
          const { labels: itemLabels, values } = extractNumericData(
            result.data,
            result.columns,
            undefined // 可以后续支持指定索引列
          );

          // 使用第一个数据集的标签作为通用标签
          if (i === 0) {
            labels = itemLabels;
          }

          // 创建数据集
          const dataset: any = {
            label: `${item.seriesName}${item.seriesUnit ? ` (${item.seriesUnit})` : ''}`,
            data: values,
            type: item.chartType,
            backgroundColor: colors[i],
            borderColor: borderColors[i],
            borderWidth: 2,
            __vizId: item.id,
          };

          // 根据图表类型设置特定属性
          if (item.chartType === 'line') {
            dataset.fill = false;
            const override = perSeriesLineOverrides[item.id];
            const dashed = override?.dashed !== undefined ? override.dashed : lineStyleOptions.dashed;
            dataset.tension = lineStyleOptions.tension;
            dataset.pointRadius = markerOptions.pointRadius;
            if (override?.pointStyle !== undefined) {
              dataset.pointStyle = override.pointStyle;
            }
            dataset.borderWidth = lineStyleOptions.borderWidth;
            if (dashed) dataset.borderDash = [6, 4];
          } else if (item.chartType === 'stepped-line') {
            dataset.type = 'line';
            dataset.fill = false;
            dataset.tension = 0;
            dataset.stepped = steppedOptions.mode;
            dataset.pointRadius = markerOptions.pointRadius;
            dataset.borderWidth = steppedOptions.borderWidth;
            const override = perSeriesLineOverrides[item.id];
            if (override?.pointStyle !== undefined) {
              dataset.pointStyle = override.pointStyle;
            }
            if (override?.dashed) dataset.borderDash = [6, 4];
          } else if (item.chartType === 'area') {
            dataset.fill = true;
            dataset.tension = 0.4;
            dataset.pointRadius = 0;
          } else if (item.chartType === 'scatter') {
            dataset.pointRadius = scatterOptions.pointRadius;
            const sOverride = perSeriesScatterOverrides[item.id];
            if (sOverride?.pointStyle) dataset.pointStyle = sOverride.pointStyle;
          } else if (item.chartType === 'bar') {
            dataset.borderRadius = 4;
          } else if (item.chartType === 'stacked') {
            // 堆叠图使用柱状图类型，并设置 stack 属性
            dataset.type = 'bar';
            dataset.stack = 'stack1'; // 所有堆叠图使用相同的 stack ID
            dataset.borderRadius = 4;
          } else if (item.chartType === 'stacked-line') {
            // 折线堆叠图：使用 line 类型并设置相同的 stack
            dataset.type = 'line';
            dataset.stack = 'stack1';
            dataset.fill = false;
            dataset.tension = 0.1;
            dataset.pointRadius = 3;
          } else if (item.chartType === 'stacked-area') {
            // 面积堆叠图：使用 line 类型并设置相同的 stack，同时填充
            dataset.type = 'line';
            dataset.stack = 'stack1';
            dataset.fill = true;
            dataset.tension = 0.4;
            dataset.pointRadius = 0;
          } else if (item.chartType === 'radar') {
            // 雷达图：所有数据集使用相同的标签，每个数据集是一个雷达图系列
            dataset.type = 'radar';
            dataset.fill = true; // 开启填充，匹配官方效果
            dataset.pointRadius = markerOptions.pointRadius;
            dataset.pointHoverRadius = 6;
            // 雷达图需要确保所有数据集使用相同的标签数量
            // 如果数据长度不一致，需要对齐或截取
          }

          datasets.push(dataset);
        }

        chartDataResult = {
          labels,
          datasets,
        };
      }

      // 设置图表数据
      setChartData(chartDataResult);

      setChartVisible(true);
      // 只在手动调用时显示成功消息
      if (showError) {
        message.success('图表生成成功');
      }
    } catch (error: any) {
      console.error('生成图表失败:', error);
      // 只在手动调用或自动调用失败时显示错误消息
      if (showError || visualizationItems.length > 0) {
        message.error(error.response?.data?.detail || '生成图表失败，请稍后重试');
      }
    } finally {
      setLoading(false);
    }
  }, [visualizationItems, allLengthsMatch, projectId, viewMode, selectedDataIndex]);

  // 使用 ref 保存最新的 handleRenderChart，避免依赖项导致的重复触发
  const handleRenderChartRef = React.useRef<typeof handleRenderChart>();
  React.useEffect(() => {
    handleRenderChartRef.current = handleRenderChart;
  }, [handleRenderChart]);

  // 当可视化项目被清空时，自动清除图表状态
  // 当有数据且长度一致时，自动生成图表
  useEffect(() => {
    if (visualizationItems.length === 0) {
      setChartData(null);
      setChartVisible(false);
      setLoading(false);
      prevVisualizationItemsKeyRef.current = '';
    } else if (allLengthsMatch && projectId && handleRenderChartRef.current) {
      // 只有当 visualizationItemsKey 真正改变时才触发画图
      if (prevVisualizationItemsKeyRef.current !== visualizationItemsKey) {
        // 先清除旧的图表，避免叠加
        setChartData(null);
        setChartVisible(false);
        prevVisualizationItemsKeyRef.current = visualizationItemsKey;
        // 当有数据且长度一致时，自动生成图表
        // 使用 ref 中的最新函数，避免因为函数引用变化而触发
        handleRenderChartRef.current();
      }
    }
    // 只依赖关键属性的变化，而不是整个数组引用或函数引用
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [visualizationItemsKey, allLengthsMatch, projectId]);

  return (
    <div style={{ padding: '16px', height: '100%', display: 'flex', flexDirection: 'column' }}>
      <div style={{ marginBottom: '16px' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: '8px' }}>
          <Title level={4} style={{ margin: 0 }}>
            数据可视化
          </Title>
          <Space>
            {visualizationItems.length > 0 && (
              <>
                <Button
                  icon={<SwapOutlined />}
                  onClick={() => {
                    if (viewMode === 'horizontal') {
                      // 从横向切换到纵向：保存当前横向模式的图表类型
                      const currentTypes: Record<string, ChartType> = {};
                      visualizationItems.forEach(item => {
                        currentTypes[item.id] = item.chartType;
                      });
                      setHorizontalChartTypes(currentTypes);
                      
                      // 恢复纵向模式的图表类型
                      visualizationItems.forEach(item => {
                        updateChartType(item.id, verticalChartType);
                      });
                    } else {
                      // 从纵向切换到横向：保存当前纵向模式的图表类型
                      if (visualizationItems.length > 0) {
                        setVerticalChartType(visualizationItems[0].chartType);
                      }

                      const currentVerticalType = visualizationItems[0]?.chartType;
                      const isRadar = currentVerticalType === 'radar';

                      if (isRadar) {
                        // 若纵向为雷达图，则横向统一切换为雷达图
                        const newTypes: Record<string, ChartType> = {};
                        visualizationItems.forEach(item => {
                          updateChartType(item.id, 'radar');
                          newTypes[item.id] = 'radar';
                        });
                        setHorizontalChartTypes(newTypes);
                      } else {
                        // 恢复横向模式的图表类型
                        visualizationItems.forEach(item => {
                          const savedType = horizontalChartTypes[item.id];
                          if (savedType) {
                            updateChartType(item.id, savedType);
                          }
                        });
                      }
                    }
                    
                    // 切换模式时清除旧的图表数据和纵向模式的数据缓存
                    setChartData(null);
                    setChartVisible(false);
                    setVerticalDataLabels([]);
                    setVerticalDataValues([]);
                    // 重置prevVisualizationItemsKey，确保下次生成图表时能触发
                    prevVisualizationItemsKeyRef.current = '';
                    setViewMode(viewMode === 'horizontal' ? 'vertical' : 'horizontal');
                  }}
                  size="small"
                  type={viewMode === 'vertical' ? 'primary' : 'default'}
                >
                  {viewMode === 'horizontal' ? '切换到纵向对比' : '切换到横向展示'}
                </Button>
                <Button onClick={handleClearAll} danger size="small">
                  清空所有
                </Button>
              </>
            )}
          </Space>
        </div>
        <Paragraph type="secondary" style={{ marginTop: 0, marginBottom: 0 }}>
          已选择 {visualizationItems.length} 条数据进行可视化
        </Paragraph>
        {firstDataLength !== null && (
          <div style={{ marginTop: '8px' }}>
            <Space>
              <Text type="secondary">数据长度：</Text>
              <Tag color="blue">{firstDataLength.toLocaleString()}</Tag>
              {!allLengthsMatch && (
                <Tag color="warning" icon={<WarningOutlined />}>
                  存在长度不一致的数据
                </Tag>
              )}
              {allLengthsMatch && visualizationItems.length > 1 && (
                <Tag color="success" icon={<CheckCircleOutlined />}>
                  所有数据长度一致
                </Tag>
              )}
            </Space>
          </div>
        )}
        {visualizationItems.length > 0 && (
          <div style={{ marginTop: '8px' }}>
            <Space>
              <Text type="secondary">{viewMode === 'vertical' ? '图表类型：' : '统一图表类型：'}</Text>
              <Select
                placeholder={viewMode === 'vertical' ? '选择图表类型' : '选择后应用到全部'}
                value={(() => {
                  if (viewMode === 'vertical' && visualizationItems.length > 0) {
                    return visualizationItems[0].chartType;
                  }
                  // 横向模式：如果所有项目的图表类型都相同，显示该类型；否则显示undefined
                  if (visualizationItems.length > 0) {
                    const firstType = visualizationItems[0].chartType;
                    const allSame = visualizationItems.every(item => item.chartType === firstType);
                    return allSame ? firstType : undefined;
                  }
                  return undefined;
                })()}
                onChange={handleChangeAllChartType}
                style={{ width: '130px' }}
                size="small"
              >
                {chartTypeOptions.map((option) => (
                  <Option key={option.value} value={option.value}>
                    <Space>
                      {option.icon}
                      {option.label}
                    </Space>
                  </Option>
                ))}
              </Select>
              {viewMode === 'vertical' && verticalDataLabels.length > 0 && (
                <>
                  <Text type="secondary" style={{ marginLeft: '16px' }}>数据组：</Text>
                  <Select
                    value={selectedDataIndex}
                    onChange={setSelectedDataIndex}
                    style={{ width: '100px' }}
                    size="small"
                  >
                    {verticalDataLabels.map((label, index) => (
                      <Option key={index} value={index}>
                        {String(label)}
                      </Option>
                    ))}
                  </Select>
                </>
              )}
            </Space>
            {viewMode === 'horizontal' && unifiedChartType && (
              <Popover
                content={
                  unifiedChartType === 'line' ? (
                    <LineStyleControls
                      visible={true}
                      lineStyleOptions={lineStyleOptions}
                      setLineStyleOptions={setLineStyleOptions}
                      markerOptions={markerOptions}
                      setMarkerOptions={setMarkerOptions}
                    />
                  ) : unifiedChartType === 'stepped-line' ? (
                    <SteppedLineControls
                      visible={true}
                      steppedOptions={steppedOptions as any}
                      setSteppedOptions={setSteppedOptions as any}
                    />
                  ) : unifiedChartType === 'scatter' ? (
                    <Space direction="vertical" size={8} style={{ width: 200 }}>
                      <Text type="secondary">标记大小</Text>
                      <Slider min={1} max={12} step={1} value={scatterOptions.pointRadius}
                        onChange={(v: number) => setScatterOptions({ pointRadius: v })} />
                    </Space>
                  ) : null
                }
                title={unifiedChartType === 'line' ? '折线图样式' : unifiedChartType === 'stepped-line' ? '阶梯折线样式' : unifiedChartType === 'scatter' ? '散点图样式' : ''}
                trigger="click"
                placement="bottomLeft"
              >
                <Button type="text" size="small" icon={<SettingOutlined />} />
              </Popover>
            )}
          </div>
        )}
        {!allLengthsMatch && inconsistentItems.length > 0 && (
          <div style={{ marginTop: '8px' }}>
            <Text type="danger" style={{ fontSize: '12px' }}>
              以下数据的长度与标准长度 ({firstDataLength?.toLocaleString()}) 不一致：
            </Text>
            <div style={{ marginTop: '4px' }}>
              {inconsistentItems.map((item, index) => (
                <Tag key={item.id} color="error" style={{ marginTop: '4px' }}>
                  {item.seriesName} (长度: {item.dataLength.toLocaleString()})
                </Tag>
              ))}
            </div>
          </div>
        )}
      </div>

      {visualizationItems.length === 0 ? (
        <div style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <Empty
            description="暂无可视化数据"
            image={Empty.PRESENTED_IMAGE_SIMPLE}
          >
            <Paragraph type="secondary" style={{ fontSize: '12px' }}>
              在实验数据列表中找到序列数据，点击"可视化"按钮添加到此处
            </Paragraph>
          </Empty>
        </div>
      ) : (
        <>
          {!allLengthsMatch && (
            <div style={{ marginBottom: '16px', marginTop: '8px' }}>
              <Text type="warning" style={{ fontSize: '12px' }}>
                <WarningOutlined /> 所有数据长度必须一致才能生成图表
              </Text>
            </div>
          )}
          {loading && (
            <div style={{ marginBottom: '16px', marginTop: '8px' }}>
              <Space>
                <Spin size="small" />
                <Text type="secondary" style={{ fontSize: '12px' }}>
                  正在生成图表...
                </Text>
              </Space>
            </div>
          )}

          <div style={{ flex: 1, overflow: 'auto' }}>
            <List
              dataSource={visualizationItems}
              renderItem={(item) => (
                <List.Item style={{ padding: '12px 0' }}>
                  <Card
                    size="small"
                    style={{ width: '100%', cursor: 'pointer' }}
                    bodyStyle={{ padding: '12px' }}
                    hoverable
                    onClick={() => {
                      navigateToSeries(item.experimentId, item.categoryId, item.seriesId);
                    }}
                  >
                    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
                      <div style={{ flex: 1 }}>
                        <div style={{ marginBottom: '8px' }}>
                          <Space>
                            <Tag color="blue">ID: {item.experimentId}</Tag>
                            <Text strong>{item.seriesName}</Text>
                            {item.seriesUnit && (
                              <Tag>{item.seriesUnit}</Tag>
                            )}
                          </Space>
                        </div>
                        <div style={{ fontSize: '12px', color: '#999' }}>
                          <Text type="secondary">
                            实验: {item.experimentName || `实验 #${item.experimentId}`}
                          </Text>
                          <Divider type="vertical" style={{ margin: '0 8px' }} />
                          <Text type="secondary">分类: {item.categoryName}</Text>
                        </div>
                      </div>
                      <Space style={{ marginLeft: '16px' }}>
                        {/* 纵向模式下隐藏每个项目的图表类型选择器 */}
                        {/* 横向模式下，如果统一图表类型是雷达图，则禁用单独选择器（雷达图只能统一选择） */}
                        {viewMode === 'horizontal' && !(unifiedChartType === 'radar') && (
                          <Select
                            value={item.chartType}
                            onChange={(value) => {
                              // 如果选择雷达图，强制应用到所有项目
                              if (value === 'radar') {
                                handleChangeAllChartType('radar');
                              } else {
                                updateChartType(item.id, value);
                                // 横向模式下，更新保存的图表类型
                                setHorizontalChartTypes(prev => ({
                                  ...prev,
                                  [item.id]: value
                                }));
                                // 图表类型变化后，会自动触发 useEffect 重新生成图表
                              }
                            }}
                            onClick={(e) => {
                              e.stopPropagation(); // 阻止触发 Card 的点击事件
                            }}
                            style={{ width: '130px' }}
                            size="small"
                          >
                            {chartTypeOptions.filter(opt => opt.value !== 'radar').map((option) => (
                              <Option key={option.value} value={option.value}>
                                <Space>
                                  {option.icon}
                                  {option.label}
                                </Space>
                              </Option>
                            ))}
                          </Select>
                        )}
                        {viewMode === 'horizontal' && unifiedChartType === 'radar' && (
                          <Tag color="blue" style={{ marginRight: '8px' }}>
                            雷达图（统一）
                          </Tag>
                        )}
                        {viewMode === 'horizontal' && (item.chartType === 'line' || item.chartType === 'stepped-line') && (
                          <Popover
                            content={
                              <Space direction="vertical" size={12} style={{ width: 200 }}>
                                <div>
                                  <Text type="secondary" style={{ fontSize: '12px' }}>线条样式</Text>
                                  <Select
                                    size="small"
                                    value={(perSeriesLineOverrides[item.id]?.dashed ?? lineStyleOptions.dashed) ? 'dashed' : 'solid'}
                                    onChange={(val) => setPerSeriesLineOverrides(prev => ({
                                      ...prev,
                                      [item.id]: { ...(prev[item.id] || {}), dashed: val === 'dashed' }
                                    }))}
                                    style={{ width: '100%', marginTop: 4 }}
                                  >
                                    <Option value="solid">实线</Option>
                                    <Option value="dashed">虚线</Option>
                                  </Select>
                                </div>
                                <div>
                                  <Text type="secondary" style={{ fontSize: '12px' }}>标记形状</Text>
                                  <Select
                                    size="small"
                                    value={perSeriesLineOverrides[item.id]?.pointStyle || 'circle'}
                                    onChange={(val) => setPerSeriesLineOverrides(prev => ({
                                      ...prev,
                                      [item.id]: { ...(prev[item.id] || {}), pointStyle: val as any }
                                    }))}
                                    style={{ width: '100%', marginTop: 4 }}
                                  >
                                    <Option value="circle">圆形</Option>
                                    <Option value="triangle">三角形</Option>
                                    <Option value="rect">矩形</Option>
                                    <Option value="rectRounded">圆角矩形</Option>
                                    <Option value="rectRot">旋转矩形</Option>
                                    <Option value="cross">十字</Option>
                                    <Option value="crossRot">旋转十字</Option>
                                    <Option value="star">星形</Option>
                                    <Option value="line">短线</Option>
                                    <Option value="dash">短划</Option>
                                  </Select>
                                </div>
                              </Space>
                            }
                            title="样式设置"
                            trigger="click"
                            placement="bottomRight"
                          >
                            <Button type="text" size="small" icon={<SettingOutlined />} onClick={(e) => e.stopPropagation()} />
                          </Popover>
                        )}
                        {viewMode === 'horizontal' && item.chartType === 'scatter' && (
                          <Popover
                            content={
                              <Space direction="vertical" size={12} style={{ width: 200 }}>
                                <div>
                                  <Text type="secondary" style={{ fontSize: '12px' }}>标记形状</Text>
                                  <Select
                                    size="small"
                                    value={perSeriesScatterOverrides[item.id]?.pointStyle || 'circle'}
                                    onChange={(val) => setPerSeriesScatterOverrides(prev => ({
                                      ...prev,
                                      [item.id]: { ...(prev[item.id] || {}), pointStyle: val as any }
                                    }))}
                                    style={{ width: '100%', marginTop: 4 }}
                                  >
                                    <Option value="circle">圆形</Option>
                                    <Option value="triangle">三角形</Option>
                                    <Option value="rect">矩形</Option>
                                    <Option value="rectRounded">圆角矩形</Option>
                                    <Option value="rectRot">旋转矩形</Option>
                                    <Option value="cross">十字</Option>
                                    <Option value="crossRot">旋转十字</Option>
                                    <Option value="star">星形</Option>
                                    <Option value="line">短线</Option>
                                    <Option value="dash">短划</Option>
                                  </Select>
                                </div>
                              </Space>
                            }
                            title="样式设置"
                            trigger="click"
                            placement="bottomRight"
                          >
                            <Button type="text" size="small" icon={<SettingOutlined />} onClick={(e) => e.stopPropagation()} />
                          </Popover>
                        )}
                        <Button
                          type="text"
                          danger
                          size="small"
                          icon={<DeleteOutlined />}
                          onClick={(e) => {
                            e.stopPropagation(); // 阻止触发 Card 的点击事件
                            removeVisualizationItem(item.id);
                          }}
                        >
                          移除
                        </Button>
                      </Space>
                    </div>
                  </Card>
                </List.Item>
              )}
            />
          </div>
        </>
      )}

      {/* 图表展示区域 */}
      {visualizationItems.length > 0 && chartVisible && chartData && !loading && (
        <div
          style={{
            marginTop: '16px',
            padding: '20px',
            paddingBottom: '80px', // 底部留出空间，避免被按钮遮挡
            background: '#fff',
            borderRadius: '4px',
            border: '1px solid #d9d9d9',
            minHeight: '500px',
            position: 'relative',
          }}
        >
          <div style={{ width: '100%', height: '100%' }}>
            
              <ChartDisplay
              viewMode={viewMode}
              chartData={chartData}
              verticalChartType={verticalChartType}
              verticalDataLabelsLength={verticalDataLabels.length}
              selectedDataIndex={selectedDataIndex}
                lineStyleOptionsKey={`${lineStyleOptions.borderWidth}-${lineStyleOptions.tension}-${lineStyleOptions.dashed}`}
                markerOptionsKey={`${markerOptions.pointRadius}`}
                steppedOptionsKey={`${steppedOptions.mode}-${steppedOptions.borderWidth}`}
                scatterOptionsKey={`${scatterOptions.pointRadius}`}
              seriesCount={chartData.datasets.length}
            />
          </div>
        </div>
      )}
      {loading && visualizationItems.length > 0 && (
        <div
          style={{
            marginTop: '16px',
            padding: '40px',
            textAlign: 'center',
            background: '#f5f5f5',
            borderRadius: '4px',
            border: '1px dashed #d9d9d9',
          }}
        >
          <Spin size="large" />
          <div style={{ marginTop: '16px' }}>
            <Text type="secondary">正在加载数据并生成图表...</Text>
          </div>
        </div>
      )}
    </div>
  );
};

export default VisualizationPanel;

